# -*- coding: utf-8 -*-

import os
from PIL import Image

class Compress_Picture(object):
    def __init__(self,imgfolder,Imtype,width,height):
        # 图片格式，可以换成.bpm等

        self.imgsPathlist = self.getImgPathList(imgfolder)
        self.imgsPath = imgfolder
        self.Imtype = Imtype
        self.width = width
        self.height = height
        if self.imgsPathlist != []:
            self.compressImage()
        # self.file = '.bmp'

    def compressImage(self):

        comdic = "%s_%s_compress/" % (self.imgsPath,self.Imtype)

        if not os.path.exists(comdic):
            os.makedirs(comdic)
        else:
            return comdic
        for filename in self.imgsPathlist:
            print(filename)

            sImg = Image.open(filename)
            # w, h = sImg.size
            dImg = sImg.resize((self.width, self.height), Image.ANTIALIAS)


            compressPicPath = comdic + os.path.basename(filename)
            dImg.save(compressPicPath,quality=100)
        return comdic

    def getImgPathList(self,imgfolder):
        folderpaths = os.listdir(imgfolder)
        imagePathList = []
        for path in folderpaths:
            if path.split('.')[-1] in ['png', 'jpg', 'bmp', 'tif', 'ico', 'jpeg']:
                path = os.path.join(imgfolder, path)
                imagePathList.append(path)
        return imagePathList

